<?php
/**
 * vanephp web framework
 * 内部视图类
 *
 * @author aray <ofree@qq.com>
 * @link http://www.vanephp.com/
 * @copyright Copyright &copy; 2010 aray
 * @license http://www.vanephp.com/license
 * @package view
 */

if ( ! defined ( 'INVANE' ) )
	exit ( '!' );

/**
 * 内部视图类
 * @author aray
 *
 */
class vane_view_inner {
	private $cache = null;
	private $config = array ();
	/**
	 * 构造方法
	 */
	public function vane_view_inner ( ) {
		$this->config = config::get ( 'config', 'view' );
		$this->cache = cache::get ( view::getCacheName ( ) );
	}
	/**
	 * 获取当前视图对象
	 */
	public function getViewer ( ) {
		return $this;
	}
	/**
	 * 获取模板引擎
	 */
	public function getTpl ( ) {
		return $this;
	}
	/**
	 * 是否缓存视图
	 */
	public function isCached ( ) {
		return $this->cache != null;
	}
	/**
	 * 渲染模板
	 */
	public function display ( ) {
		# 如果动作为默认动作，优先     控制器名_动作名.tpl (不存在时，使用  控制器名.tpl)
		$tplDir = isset ( $this->config['template_dir'] ) ? $this->config['template_dir'] : '';
		$tplDir .= DS;
		$tplname = '';
		if ( dispatcher::getAction ( ) == config::get ( 'default_action' ) ) {
			$firstTpl = $tplDir . dispatcher::getController ( ) . '.php';
			if ( file_exists ( $firstTpl ) ) {
				$tplname = $firstTpl;
			} else {
				$tplname .= $tplDir . dispatcher::getController ( ) . '_' . dispatcher::getAction ( ) . '.php';
			}
		} else {
			$tplname .= $tplDir . dispatcher::getController ( ) . '_' . dispatcher::getAction ( ) . '.php';
		}
		
		$lifetime = isset ( $this->config['lifetime'] ) ? ( int ) $this->config['lifetime'] : 0;
		$lifetime = $lifetime >= 0 ? $lifetime : 0;
		
		# 不缓存时，直接跳过缓存测试
		if ( $lifetime == 0 ) {
			$this->cache = null;
		}
		
		if ( $this->cache ) {
		
		} else {
			foreach ( view::$VARS as $k => $v ) {
				$GLOBALS[$k] = $v;
			}
			include $tplname;
			$this->cache = ob_get_contents ( );
			ob_clean ( );
			if ( $lifetime > 0 ) {
				cache::set ( view::getCacheName ( ), $this->cache, $lifetime );
			}
		}
		//		header ( "Content-Length: " . strlen ( $this->cache ) );
		echo $this->cache;
		exit ( );
	}
}